package org.example.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.dao.BookDao;
import org.example.dao.DiscussionDao;
import org.example.dao.UserDao;
import org.example.domain.Book;
import org.example.domain.Discussion;
import org.example.domain.PageBean;
import org.example.domain.User;
import org.example.domain.response.ResponseResult;
import org.example.services.SaveService;
import org.example.utils.PageConvertPageBeanUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
@Transactional
public class SaveServiceImpl implements SaveService {

    @Resource
    private UserDao userDao;
    @Resource
    private BookDao bookDao;
    @Resource
    private DiscussionDao discussionDao;

    @Override
    public ResponseResult saveUserBook(int userId, int bookId) {
        try {
            User user = userDao.selectById(userId);
            if(user == null){
                log.info("用户收藏书籍：用户不存在");
                return ResponseResult.failed("用户ID不存在");
            }
            Book book = bookDao.selectById(bookId);
            if(book == null){
                log.info("用户收藏书籍：书籍不存在");
                return ResponseResult.failed("书籍ID不存在");
            }
            int exit = userDao.getUserBookById(userId,bookId);
            if(exit >= 1){
                log.info("用户收藏书籍：书籍{}:{}已被{}:{}收藏",book.getBookId(),book.getName(),user.getUserId(),user.getUsername());
                return ResponseResult.failed("书籍已被收藏");
            }
            userDao.saveUserBook(userId,bookId);
            log.info("用户收藏书籍：{}:{}收藏了{}:{}",user.getUserId(),user.getUsername(),book.getBookId(),book.getName());
            return ResponseResult.success("书籍收藏成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("用户收藏书籍：失败");
            return ResponseResult.failed("收藏书籍失败");
        }
    }

    @Override
    public ResponseResult deleteUserBook(int userId, int bookId) {
        try {
            User user = userDao.selectById(userId);
            if(user == null){
                log.info("删除用户收藏书籍：用户不存在");
                return ResponseResult.failed("用户ID不存在");
            }
            Book book = bookDao.selectById(bookId);
            if(book == null){
                log.info("删除用户收藏书籍：书籍不存在");
                return ResponseResult.failed("书籍ID不存在");
            }
            int exit = userDao.getUserBookById(userId,bookId);
            if(exit < 1){
                log.info("删除用户收藏书籍：书籍{}:{}未被{}:{}收藏",book.getBookId(),book.getName(),user.getUserId(),user.getUsername());
                return ResponseResult.failed("书籍未被收藏");
            }
            userDao.deleteUserBook(userId,bookId);
            log.info("删除用户收藏书籍：{}:{}取消收藏{}:{}",user.getUserId(),user.getUsername(),book.getBookId(),book.getName());
            return ResponseResult.success("书籍取消收藏成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("删除用户收藏书籍：失败");
            return ResponseResult.failed("取消收藏书籍失败");
        }
    }

    @Override
    public ResponseResult getUserSaveBooks(int userId, int currentPage) {
        try {
            User user = userDao.selectById(userId);
            if(user == null){
                log.info("获取用户收藏书籍：用户不存在");
                return ResponseResult.failed("用户ID不存在");
            }
            List<Integer> bookIds = userDao.getUserSaveBooks(userId);
            Page<Book> page = new Page<>(currentPage, 10);
            LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
            for (Integer bookId : bookIds) {
                bookLambdaQueryWrapper.eq(Book::getBookId,bookId).or();
            }
            Page<Book> bookPage = bookDao.selectPage(page, bookLambdaQueryWrapper);
            PageBean<Book> bookPageBean = new PageBean<>();
            bookPageBean.setCurrentPage((int) bookPage.getCurrent());
            bookPageBean.setPageSize((int) bookPage.getSize());
            bookPageBean.setTotalPages((int) bookPage.getPages());
            bookPageBean.setTotalData((int) bookPage.getTotal());

            List<Book> rows = bookPage.getRecords();
            for (Book row : rows) {
                List<String> bookType = bookDao.getBookType(row.getBookId());
                row.setType(bookType);
            }
            bookPageBean.setRows(rows);
            log.info("获取用户收藏书籍：获取{}：{}收藏书籍{}",userId,user.getUsername(),bookIds);
            return ResponseResult.success("获取收藏书籍成功",bookPageBean);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("获取用户收藏书籍：失败");
            return ResponseResult.failed("获取收藏书籍失败");
        }
    }

    @Override
    public ResponseResult saveUserDiscussion(int userId, int discussionId) {
        try {
            User user = userDao.selectById(userId);
            if(user == null){
                log.info("用户收藏讨论：用户不存在");
                return ResponseResult.failed("用户ID不存在");
            }
            Discussion discussion = discussionDao.selectById(discussionId);
            if(discussion == null){
                log.info("用户收藏讨论：讨论不存在");
                return ResponseResult.failed("讨论ID不存在");
            }
            int exit = userDao.getUserDiscussionById(userId,discussionId);
            if(exit >= 1){
                log.info("用户收藏讨论：讨论{}:{}已被{}:{}收藏",discussion.getDiscussionId(),discussion.getTitle(),user.getUserId(),user.getUsername());
                return ResponseResult.failed("讨论已被收藏");
            }
            userDao.saveUserDiscussion(userId,discussionId);
            log.info("用户收藏讨论：{}:{}收藏了{}:{}",user.getUserId(),user.getUsername(),discussion.getDiscussionId(),discussion.getTitle());
            return ResponseResult.success("讨论收藏成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("用户收藏讨论：失败");
            return ResponseResult.failed("收藏讨论失败");
        }
    }

    @Override
    public ResponseResult deleteUserDiscussion(int userId, int discussionId) {
        try {
            User user = userDao.selectById(userId);
            if(user == null){
                log.info("删除用户收藏讨论：用户不存在");
                return ResponseResult.failed("用户ID不存在");
            }
            Discussion discussion = discussionDao.selectById(discussionId);
            if(discussion == null){
                log.info("删除用户收藏讨论：讨论不存在");
                return ResponseResult.failed("书籍ID不存在");
            }
            int exit = userDao.getUserDiscussionById(userId,discussionId);
            if(exit < 1){
                log.info("删除用户收藏讨论：讨论{}:{}未被{}:{}收藏",discussion.getDiscussionId(),discussion.getTitle(),user.getUserId(),user.getUsername());
                return ResponseResult.failed("讨论未被收藏");
            }
            userDao.deleteUserDiscussion(userId,discussionId);
            log.info("删除用户收藏讨论：{}:{}取消收藏{}:{}",user.getUserId(),user.getUsername(),discussion.getDiscussionId(),discussion.getTitle());
            return ResponseResult.success("讨论取消收藏成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("删除用户收藏讨论：失败");
            return ResponseResult.failed("取消收藏讨论失败");
        }
    }

    @Override
    public ResponseResult getUserDiscussion(int userId, int currentPage) {
        try {
            User user = userDao.selectById(userId);
            if(user == null){
                log.info("获取用户收藏书籍：用户不存在");
                return ResponseResult.failed("用户ID不存在");
            }
            List<Integer> discussionIds = userDao.getUserSaveDiscussion(userId);
            Page<Discussion> page = new Page<>(currentPage, 10);
            LambdaQueryWrapper<Discussion> discussionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            for (Integer discussionId : discussionIds) {
                discussionLambdaQueryWrapper.eq(Discussion::getDiscussionId,discussionId).or();
            }
            Page<Discussion> discussionPage = discussionDao.selectPage(page, discussionLambdaQueryWrapper);
            PageBean<Discussion> discussionPageBean = PageConvertPageBeanUtil.convert(discussionPage);
            log.info("获取用户收藏书籍：获取{}：{}收藏书籍{}",userId,user.getUsername(),discussionIds);
            return ResponseResult.success("获取收藏书籍成功",discussionPageBean);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("获取用户收藏书籍：失败");
            return ResponseResult.failed("获取收藏书籍失败");
        }
    }
}
